package com.wss.module.main.ui.view.ca;

import com.wss.common.utils.ColorUtils;
import ohos.agp.colors.ColorConverter;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.BlendMode;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Path;
import ohos.agp.utils.Color;
import ohos.agp.utils.Rect;
import ohos.app.Context;
import org.jetbrains.annotations.NotNull;

public abstract class AbstractOverlayView extends Component implements Component.DrawTask {

    private Path mPath = new Path();

    private Paint mPaint;

    private Paint mBackgroundPaint;

    private Color mBackgroundColor = Color.BLACK;

    public AbstractOverlayView(Context context) {
        this(context, null);
    }

    public AbstractOverlayView(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public AbstractOverlayView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init();
        addDrawTask(this);
    }

    private void init() {
        this.mPaint = new Paint();
        this.mPaint.setStyle(Paint.Style.STROKE_STYLE);
        this.mPaint.setColor(Color.BLACK);
        this.mPaint.setStrokeWidth(2);
    }

    private Paint getBackgroundPaint() {
        if (this.mBackgroundPaint != null) {
            return mBackgroundPaint;
        }
        this.mBackgroundPaint = new Paint();
        mBackgroundPaint.setAntiAlias(true);
        mBackgroundPaint.setStyle(Paint.Style.FILL_STYLE);
        mBackgroundPaint.setColor(mBackgroundColor);
        return mBackgroundPaint;
    }

    protected abstract void buildPath(@NotNull final Path path, final int viewWidth,
                                      final int viewHeight);

    public abstract Rect getMaskBounds();

    /**
     * Set background color.
     *
     * @param color color.
     */
    public void setBackgroundColor(final int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(ColorUtils.colorToRgbColor(color));
        this.mBackgroundColor = new Color(color);

        this.invalidate();
    }

    /**
     * Set mask path color.
     *
     * @param color color
     */
    public void setMaskPathColor(final int color) {
        this.mPaint.setColor(new Color(color));

        this.invalidate();
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        canvas.save();

        mPath.reset();

        buildPath(mPath, getWidth(), getHeight());

        canvas.clipPath(mPath, Canvas.ClipOp.DIFFERENCE);
        canvas.drawColor(mBackgroundColor.getValue(), BlendMode.SRC_OVER);
        canvas.restore();
        canvas.drawPath(mPath, mPaint);
    }
}
